//
//  ShowPhotoAnimator.swift
//  weibo1
//
//  Created by 李进 on 15/11/4.
//  Copyright © 2015年 李进. All rights reserved.
//

import Foundation
import UIKit

class ShowPhotoAnimator:NSObject, UIViewControllerTransitioningDelegate{
    
    private var isPresented = false
    
    //返回 modal 展现的动画实现体
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    //dismiss 展现的动画实现体
    //parameter transitioncontext ：转场动画的上下文 － 提供动画所需要的素材
    /**
    1.容器视图 － 会将 modal 要展现的视图包装在容器视图中
    存放的视图要显示 － 必须自己指定大小！ 不会通过自动布局填充满屏
    2. viewcontrollforkey ：fromvc／tovc
    3. viewfoekey： fromview／toview
    4. completetransition：无论转场是否被取消，都必须调用
    否则，系统不做其他事件的处理
    */
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    
}

extension ShowPhotoAnimator:UIViewControllerAnimatedTransitioning{
    
    //动画时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
       return 2
    }
    
    //具体的动画实现效果 － 一旦实现这个方法所有的动画代码都交由程序员来实现
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        //这边来实现 modal 和 dismiss 的动画效果
        isPresented ? presentAnimation(transitionContext) : dismissAnimation(transitionContext)
    }
    
    //定义 modal 的展现动画
   private func presentAnimation(transitionContext:UIViewControllerContextTransitioning){
    
    //1.获取需要modal 的视图也是需要展现的视图控制器的根视图
    let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
    toView.alpha = 0
    //2. 将获取到的视图添加到视图容器中去
    
    transitionContext.containerView()?.addSubview(toView)
    //3.开始动画
     UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
        toView.alpha = 1
        }) { (_) -> Void in
            
            //这边一定要告诉系统转场动画完成
            transitionContext.completeTransition(true)
            
    }
    }
    
    //定义需要的解除转场动画的实现方法
    private func dismissAnimation(transitionContext:UIViewControllerContextTransitioning){
        
        //1.获取需要 dismiss 的控制器的根视图
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        
        //3.开始动画
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            fromView.alpha = 0
            }) { (_) -> Void in
                
                //将 fromview 从父视图中删除
                fromView.removeFromSuperview()
                
                //告诉系统动画完成
                transitionContext.completeTransition(true)
                
        }
    }
    
    
    
    
    
    
}